package cc.jcizp.userservice.service.impl;

import cc.jcizp.userservice.dao.UserDao;
import cc.jcizp.userservice.domain.User;
import cc.jcizp.userservice.dto.ExecutionResult;
import cc.jcizp.userservice.enums.ExecutionStateEnum;
import cc.jcizp.userservice.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl implements UserService {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private UserDao userDao;

    @Override
    public ExecutionResult registerUser(User user) {
        ExecutionResult executionResult = null;
        ExecutionStateEnum executionStateEnum = null;
        logger.info("before register [company_id:" + user.getApp_id() + ",user_name:" + user.getUser_name() + "]");
        int resultCode = userDao.insertUser(user);
        if(resultCode <= 0){
            User resultUser = userDao.findUserById(user);
            if(resultUser != null){
                executionStateEnum = ExecutionStateEnum.NAME_EXIST;
            }else{
                executionStateEnum = ExecutionStateEnum.FAIL;
            }
            executionResult = new ExecutionResult(executionStateEnum,null);
            logger.info("register [company_id:" + user.getApp_id() + ",user_name:" + user.getUser_name() + "]" + " fail,Reason:" + executionStateEnum.getInfo());
        }else{
            executionResult = new ExecutionResult(ExecutionStateEnum.SUCCESS,user);
            logger.info("register [company_id:" + user.getApp_id() + ",user_name:" + user.getUser_name() + "]" + " success");
        }
        return executionResult;
    }

    @Override
    public ExecutionResult authentication(User user) {
        ExecutionResult executionResult = null;
        ExecutionStateEnum executionStateEnum = null;
        logger.info("before authentication [company_id:" + user.getApp_id() + ",user_name:" + user.getUser_name() + "]");
        User findUser = userDao.authentication(user);
        if(findUser == null){
            executionStateEnum = ExecutionStateEnum.AUTHENTICATION_FAIL;
            logger.info("authentication [company_id:" + user.getApp_id() + ",user_name:" + user.getUser_name() + "]" + " fail,Reason:" + executionStateEnum.getInfo());
        }else{
            executionStateEnum = ExecutionStateEnum.SUCCESS;
            logger.info("authentication [company_id:" + user.getApp_id() + ",user_name:" + user.getUser_name() + "]" + " success");
        }
        executionResult = new ExecutionResult(executionStateEnum,findUser);
        return executionResult;
    }
}
